package org.jsola.hr.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Component
public class HrEmpLoginInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(HrEmpLoginInterceptor.class);

//    @Value("${jwt.token-header}")
//    private String tokenHeader;
//
//    @Value("${jwt.expire}")
//    private int expire;
//
//    @Autowired
//    private JwtTokenUtil jwtTokenUtil;
//
//    @Autowired
//    private RedisTemplate<String, String> redisTemplate;
//
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws JsolaException, Exception {
//        try{
//            HandlerMethod handlerMethod = null;
//            if (handler instanceof HandlerMethod) {
//                handlerMethod = (HandlerMethod) handler;
//            }else{
//                logger.info("请求接口不存在");
//                response.setCharacterEncoding("UTF-8");
//                response.setContentType("application/json;charset=UTF-8");
//                JsonResult jsonResult = new JsonResult(404, "请求接口不存在");
//                response.getWriter().write(JSON.toJSONString(jsonResult));
//                return false;
//            }
//            // 配置该注解，说明不进行用户拦截
//            IgnoreUserToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreUserToken.class);
//            if (annotation == null) {
//                annotation = handlerMethod.getMethodAnnotation(IgnoreUserToken.class);
//            }
//            if (annotation != null) {
//                return super.preHandle(request, response, handler);
//            }
//            String token = request.getHeader(tokenHeader);
//            logger.info(token);
//            if (StringUtils.isEmpty(token)) {
//                if (request.getCookies() != null) {
//                    for (Cookie cookie : request.getCookies()) {
//                        if (cookie.getName().equals(tokenHeader)) {
//                            token = cookie.getValue();
//                        }
//                    }
//                }
//            }
//
//            IJWTInfo infoFromToken = jwtTokenUtil.getInfoFromTokenTmp(token);
//            //redis验证token有效性
//            Object obj = redisTemplate.boundValueOps("token:appUser:" + infoFromToken.getUniqueName()).get();
//            String tokenOld = obj == null ? "" : obj.toString();
//            if(tokenOld.equals(token)){
//                request.setAttribute("appUserId", infoFromToken.getId());
//                redisTemplate.expire("token:appUser:" + infoFromToken.getUniqueName(), expire, TimeUnit.MINUTES);
//            }else{
////                throw new JsolaException("User token expired!", 40101);
//                throw new JsolaException("登录信息过期，请重新登陆！", 40101);
//            }
////            request.setAttribute("appUserId", infoFromToken.getId());
//        }catch (JsolaException me){
//            logger.info(me.getMessage());
//            response.setCharacterEncoding("UTF-8");
//            response.setContentType("application/json;charset=UTF-8");
//            JsonResult jsonResult = new JsonResult(me.getStatus(), me.getMessage());
//            response.getWriter().write(JSON.toJSONString(jsonResult));
//            return false;
//        }catch (Exception e){
//            e.printStackTrace();
//            logger.info(e.getMessage());
//            response.setCharacterEncoding("UTF-8");
//            response.setContentType("application/json;charset=UTF-8");
//            JsonResult jsonResult = new JsonResult(500, e.getMessage());
//            response.getWriter().write(JSON.toJSONString(jsonResult));
//            e.printStackTrace();
//            return false;
//        }
//
////        BaseContextHandler.setUsername(infoFromToken.getUniqueName());
////        BaseContextHandler.setName(infoFromToken.getName());
////        BaseContextHandler.setUserID(infoFromToken.getId());
//        return super.preHandle(request, response, handler);
//    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
